package com.wangrui.config;

import com.wangrui.pojo.School;
import com.wangrui.pojo.User;
import com.wangrui.service.SchoolService;
import com.wangrui.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName CustomUserDetailsService
 * @Description TODO
 * @Author 王锐
 * @Date DATE{TIME}
 */
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    UserService userService;

    @Autowired
    private SchoolService schoolService;

    @Autowired
    HttpServletRequest request;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userService.selectUser(username);
        System.out.println(user.getUsername());
        if (user == null){
            throw new UsernameNotFoundException("用户名不存在!");
        }
        HttpSession session = request.getSession();


        School school = schoolService.getSchoolName(user.getSid());
        session.setAttribute("school", school);
        session.setAttribute("user",user);
       // session.setAttribute("sessusername",username);
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
//        for (Role role:user.getRoles()) {
//            authorities.add(new SimpleGrantedAuthority(role.getName()));
//        }
        authorities.add(new SimpleGrantedAuthority("ROLE_"+"1"));//需要加上 "ROLE_"
        System.out.println(user.getUsername()+authorities.toString());
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),authorities);
    }
}
